accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
filename = ''
key = ''
expire = 0
g_object_name = ''

now = timestamp = Date.parse(new Date()) / 1000;

function send_request() {
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (xmlhttp != null) {
		serverUrl = '../../postObjectPolicy.action'
		xmlhttp.open("GET", serverUrl, false);
		xmlhttp.send(null);
		return xmlhttp.responseText
	} else {
		alert("Your browser does not support XMLHTTP.");
	}
};

function get_signature() {
	//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
	now = timestamp = Date.parse(new Date()) / 1000;
	if (expire < now + 3) {
		body = send_request();
		var obj = eval("(" + body + ")");
		host = obj['host']
		policyBase64 = obj['policy']
		accessid = obj['accessid']
		signature = obj['signature']
		expire = parseInt(obj['expire'])

		key = obj['dir']
		
		
		return true;
	}
	return false;
};

function random_string(len) {　　
	len = len || 32;　　
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
	var maxPos = chars.length;　　
	var pwd = '';　　
	for (i = 0; i < len; i++) {　　
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

function get_suffix(filename) {
	pos = filename.lastIndexOf('.')
	suffix = ''
	if (pos != -1) {
		suffix = filename.substring(pos)
	}
	return suffix;
}

function calculate_object_name(filename) {

	suffix = get_suffix(filename)
	g_object_name = key + random_string(10) + suffix

	return ''
}

function set_upload_param(up, filename, ret) {
	if(document.getElementById("zxName").value.replace(/\s+/g, "").length==0){
		alert("请填写奖项名称");
		return ;
	}else if(document.getElementById("zxJb").value.replace(/\s+/g, "").length==0){
		alert("请填写奖项级别");
		return ;
	}else if(document.getElementById("zxDate").value.replace(/\s+/g, "").length==0){
		alert("请填写获奖时间");
		return ;
	}else if(document.getElementById("zxOrg").value.replace(/\s+/g, "").length==0){
		alert("请填写组织单位");
		return ;
	}else if(document.getElementById("zxDj").value.replace(/\s+/g, "").length==0){
		alert("请填写获奖等级");
		return ;
	}else if($("#ossfile").is(":empty") && $("#zxFiles").val()==''){
		alert("请选择佐证材料");
		return ;
	}else if($("#ossfile").is(":empty") && !$("#zxFiles").val()==''){//只修改不上传
		submitFormAdvance();//提交表单
	} else {
		if (ret == false) {
			ret = get_signature()
		}

		if (filename != '') {

			calculate_object_name(filename)
		}
		new_multipart_params = {
			'key': g_object_name,
			'policy': policyBase64,
			'OSSAccessKeyId': accessid,
			'success_action_status': '200', //让服务端返回200,不然，默认会返回204
			'signature': signature,
		};

		up.setOption({
			'url': host,
			'multipart_params': new_multipart_params
		});

		up.start();
	}
	
}
var deletePic = function(file) {
	var c = document.getElementById(file);
	uploader.removeFile(file);
	document.getElementById('ossfile').removeChild(c);

};
var uploader = new plupload.Uploader({
	runtimes: 'html5,flash,silverlight,html4',
	browse_button: 'selectfiles',
	multi_selection: true,
	container: document.getElementById('container'),
	flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
	url: 'http://oss.aliyuncs.com',

	filters: {
		mime_types: [ //只允许上传图片和zip,rar文件
			{
				title: "Image files",
				extensions: "jpg,gif,png,bmp"
			}
		],
		max_file_size: '10mb', //最大只能上传10mb的文件
		prevent_duplicates: true //不允许选取重复文件
	},

	init: {
		PostInit: function() {
			document.getElementById('ossfile').innerHTML = '';
			document.getElementById('postfiles').onclick = function() {
				set_upload_param(uploader, '', false);
				return false;
			};
		},

		FilesAdded: function(up, files) {
			//consolse.log(files);
			plupload.each(files, function(file) {
				document.getElementById('ossfile').innerHTML = document.getElementById('ossfile').innerHTML+'<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>' + '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' + '</div>';
			});
		},
		BeforeUpload: function(up, file) {
			
			set_upload_param(up, file.name, true);
			
		},

		UploadProgress: function(up, file) {
		
			var d = document.getElementById(file.id);
			d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
			var prog = d.getElementsByTagName('div')[0];
			var progBar = prog.getElementsByTagName('div')[0]
			progBar.style.width = 2 * file.percent + 'px';
			progBar.setAttribute('aria-valuenow', file.percent);
		},

		FileUploaded: function(up, file, info) {
			//console.log(file);
			if (info.status == 200) {
				//改
				document.getElementById("zxFiles").value=document.getElementById("zxFiles").value+"http://swyt.img-cn-hangzhou.aliyuncs.com/" + g_object_name + "@!ph400"+";";
			
				setTimeout(function() {
					document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功！';
					document.getElementById(file.id).querySelector(".progress").style.display = "none";
					document.getElementById(file.id).querySelector(".btn").style.display = "none";
					document.getElementById("container").style.display = "none";
				}, 1000);
				//submitFormAdvance();//提交表单
			} else {
				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
			}
		},

		Error: function(up, err) {
			if (err.code == -600) {
				document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
			} else if (err.code == -601) {
				document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
			} else if (err.code == -602) {
				document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
			} else {
				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
			}
		},
		UploadComplete:function(uploader,files){
			if(document.getElementById("zxFiles").value=="")
				alert("上传失败");
			else{
				alert("上传成功");
				submitFormAdvance();//提交表单
			}
			
		}
	}
});

uploader.init();